import { ref, onMounted, onUnmounted, reactive } from "vue";
import ResizeObserver from 'resize-observer-polyfill';

type Size = { width?: number, height?: number };

export function useSize(onResize?: (size: Size) => any) {
  const el = ref(null);
  let dom: HTMLElement;
  const size: Size = reactive({ width: undefined, height: undefined })

  const ro = new ResizeObserver((entries) => {
    for (const entry of entries) {
      const target = entry.target;
      size.width = target.clientWidth;
      size.height = target.clientHeight;
      onResize && onResize(size)
    }
  })

  onMounted(() => {
    if (!el.value) return
    dom = el.value as unknown as HTMLElement;
    ro.observe(dom);
  })
  onUnmounted(() => {
    ro.disconnect();
  })
  return { el, size }
}

export default useSize